import {
  Text,
  View,
  StyleSheet,
  TextInput,
  Image,
  TouchableOpacity,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import React, { useState, useEffect } from "react";
import { LinearGradient } from "expo-linear-gradient";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { useRouter } from "expo-router"; // 引入 useRouter
import useCaptchaCountdown from "@/hooks/useCaptchaCountdown";
import useInputWithDone from "@/hooks/useInputWithDone";
import { useDispatch } from "react-redux";
import { setUser } from "../../store/user/actions";
import { ToastAPI } from "@/components/Toast";
import { loginFnApi } from "./api";
import { useTranslation } from "react-i18next";

import HeaderWithLanguageSelector from "@/components/HeaderWithLanguageSelector";
import { getLoginVerifyFnAPi } from "./api";
export default function Login() {
  const { t } = useTranslation();

  const router = useRouter(); // 获取路由对象
  const dispatch = useDispatch();

  const { countdown, isDisabled, handleGetCaptcha, verifyId } =
    useCaptchaCountdown(getLoginVerifyFnAPi);
  const [username, setUsername, handleUsernameDone] = useInputWithDone() as any;
  const [password, setPassword, handlePasswordDone] = useInputWithDone() as any;
  const [captChaCode, setCaptChaCode, handleCaptChaCodeDone] =
    useInputWithDone() as any;

  // 在这里处理登录逻辑
  const handleLogin = async () => {
    if (!username || !password || !captChaCode) {
      ToastAPI.warning(t("login.loginRequired"));
      return;
    }
    ToastAPI.loading(t("login.loginLoading"), "center", -1);
    try {
      const res: any = await loginFnApi({
        account: username,
        loginPassword: password,
        verifyCode: captChaCode,
        verifyId: verifyId as any,
      });
      ToastAPI.close();
      if (res.code === 0) {
        const info = res.result;
        const token = info.token;
        dispatch(setUser(token, info));
        router.replace("/(tabs)");
        ToastAPI.success(t("login.loginSuccess"));
      } else {
        ToastAPI.error(res?.errMsg || t("login.loginError"));
      }
    } catch (error) {
      ToastAPI.close();
      // 捕获错误并关闭加载提示
      ToastAPI.error(JSON.stringify(error) || t("login.requestError"));
    }
  };
  //新用户注册

  const handleRegister = () => {
    router.push("/(auth)/register");
  };
  const handleForgotPassword = () => {
    router.push("/(auth)/forgotpsw");
  };

  return (
    <PageContainer>
      <View className="bg-[#000] flex-1" style={styles.main}>
        <View className="items-center flex-row h-[46px]">
          <Text className="w-[25px]"></Text>
          <View className="flex-1 flex-row justify-center">
            <Image
              source={require("@/assets/images/logo-icon.png")}
              className="w-[68px] h-[18px]"
            />
          </View>
          <HeaderWithLanguageSelector></HeaderWithLanguageSelector>
        </View>
        {/* 使用 KeyboardAwareScrollView 包裹内容 */}
        <KeyboardAwareScrollView
          contentContainerStyle={styles.scrollContainer}
          extraHeight={100}
        >
          <View>
            <Text style={styles.title}>{t("login.title")}</Text>
            <Text className="text-[#D7D7D7] text-[16px] mt-[15px]">
              {t("login.title-tip")}
            </Text>
          </View>
          <View>
            <Text className="mt-[46px] text-[#D7D7D7] text-[16px]">
              {t("login.input.account")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handleUsernameDone}
              blurOnSubmit={true}
              placeholder={t("login.input.account.placeholder")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={username}
              onChangeText={setUsername}
            />
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("login.input.password")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              placeholder={t("login.input.password.placeholder")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={password}
              secureTextEntry
              returnKeyType="done"
              onSubmitEditing={handlePasswordDone}
              blurOnSubmit={true}
              onChangeText={setPassword}
            />
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("login.input.captcha")}
            </Text>
            <View className="flex-row justify-between items-center bg-[#25262A] rounded-[10px] h-[50px] mt-[15px] px-[12px]">
              <TextInput
                style={[{ fontSize: 16, color: "#fff", flex: 1 }]}
                placeholder={t("login.input.captcha.placeholder")}
                placeholderTextColor={"rgba(255,255,255,0.3)"}
                value={captChaCode}
                onChangeText={setCaptChaCode}
                returnKeyType="done"
                onSubmitEditing={handleCaptChaCodeDone}
                blurOnSubmit={true}
                maxLength={6}
                keyboardType="numeric"
              />
              <TouchableOpacity
                onPress={() => handleGetCaptcha(username)}
                disabled={isDisabled}
              >
                <Text className="text-[#6FC2FA] w-[80px]">
                  {countdown > 0
                    ? `${countdown}s后重试`
                    : t("login.button.getCaptcha")}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          <View className="flex-row mt-[22px] justify-between">
            <TouchableOpacity onPress={handleRegister}>
              <Text className="text-[#fff]">{t("login.link.register")}</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={handleForgotPassword}>
              <Text className="text-[#fff]">
                {t("login.link.forgotPassword")}
              </Text>
            </TouchableOpacity>
          </View>
          <TouchableOpacity onPress={handleLogin}>
            <LinearGradient
              style={styles.loginBtn}
              colors={["#3D7FFF", "#6FC2FA"]}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
            >
              <Text className="text-[#fff] text-[16px]">
                {t("login.button.login")}
              </Text>
            </LinearGradient>
          </TouchableOpacity>
        </KeyboardAwareScrollView>
      </View>
    </PageContainer>
  );
}

const styles = StyleSheet.create({
  scrollContainer: {
    flexGrow: 1, // 使内容能够伸展
  },
  main: {
    paddingLeft: 13,
    paddingRight: 13,
  },

  title: {
    fontSize: 24,
    color: "#fff",
    fontWeight: 600,
    paddingTop: 53,
  },
  input: {
    height: 50,
    backgroundColor: "#25262A",
    borderRadius: 10,
    marginTop: 15,
  },
  loginBtn: {
    height: 50,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22,
  },
});
